import { computed, ref } from "vue";
import { storeToRefs } from "pinia";
import { usePlanetSchematicsStore } from "../../../src/cache";
import type { Ref } from "vue";
import type { TreeInstance } from "@chulei-ui/element-plus";
import type { PlanetResourceTreeItem } from "./types";

// 1033 1032 1035 p0
// 1042 p1
// 1034 p2
// 1040 p3
// 1041 p4
const groupIds: number[][] = [[1032, 1033, 1035], [1042], [1034], [1040], [1041]];

export const usePlanetTree = (model: Ref<PlanetResourceTreeItem[] | undefined>, props: { level: number }) => {
  const treeRef = ref<TreeInstance>();
  const planetSchematicsStore = usePlanetSchematicsStore();
  const { planetSchematics } = storeToRefs(planetSchematicsStore);
  const onCheckedChange = () => {
    model.value = treeRef.value!.getCheckedNodes() as PlanetResourceTreeItem[];
  };

  const root = computed(() => {
    return planetSchematics.value.filter((e) => groupIds[props.level].includes(e.group_id));
  });

  const treeData = computed(() => {
    return root.value.map((p) => {
      return {
        id: p.id,
        label: p.name,
        quantity: 1,
        children: formatTreeData(p.inputs, 1),
      };
    });
  });

  const formatTreeData = (nodes: { id: number; name: string; quantity: number }[], count: number): any => {
    return nodes.map((node) => {
      const quantity = node.quantity * count;
      const item = planetSchematicsStore.getById(node.id);
      return {
        id: node.id,
        label: node.name,
        quantity,
        children: item?.inputs ? formatTreeData(item?.inputs, quantity / item!.output.quantity) : [],
      };
    });
  };

  return { treeRef, onCheckedChange, treeData };
};
